<?php

/**
 * A simple static class containing a PDO database.
 */
class Database {
	private static $db;
	
	/**
	 * Gets or creates an active database connection.
	 * 
	 * @return	A database connection
	 */
	public static function getDB() {
		// Check if we need to establish a connection:
		if (!self::$db) {
			// Establish connection:
			Logger::log("database", "Establishing database connection.");
			self::$db = new PDO(SETTINGS_PDOCONNECTIONSTRING, SETTINGS_DBUSER, SETTINGS_DBPASS);
			self::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			
			// Check for errors:
			$error = self::$db->errorInfo();
			if($error[0] != "") {
				Logger::log("database", "Unable to establish connection: " . $error);
				throw new PCException("Unable to establish connection: " . $error, 500);
			} else {
				Logger::log("database", "Connection established.");
			}
		}
		
		// Return connection:
		return self::$db;
	}
	
	
	
	/**
	 * Logs a message to the activity log.
	 * 
	 * @param type		The type of activity (name of the operation).
	 * @param userid	The user performing the activity.
	 * @param token		The token under which the activity was performed.
	 * @param data		Any data corresponding to the activity.
	 */
	public static function logActivity($type, $userid, $token, $data) {
		if (!$type) {
			throw new PCException("Missing 'type' parameter in Database->logActivity().", 500);
		} else if (!is_numeric($userid)) {
			throw new PCException("Missing 'userid' parameter in Database->logActivity().", 500);
		} else if (!$token) {
			throw new PCException("Missing 'token' parameter in Database->logActivity().", 500);
		} else if (!$data) {
			throw new PCException("Missing 'data' parameter in Database->logActivity().", 500);
		}
		
		$db = Database::getDB();
		$stmt = $db->prepare("INSERT INTO Activity (type, userid, token, data, tstamp) VALUES (:type, :userid, :token, :data, :tstamp)");
		$stmt->bindValue(":type", $type);
		$stmt->bindValue(":userid", $userid);
		$stmt->bindValue(":token", $token);
		$stmt->bindValue(":data", $data);
		$stmt->bindValue(":tstamp", microtime(true));
		if (!$stmt->execute()) {
			$err = $stmt->errorInfo();
			Logger::log("database", "Activity NOT logged:" . $err[2]);
		} else {
			Logger::log("database", "Activity logged.");
		}
	}
}